package com.elinkway.infinitemovies.ui.activity.play;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bean.PlayData;
import com.elinkway.infinitemovies.utils.CDEManager;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.TrafficStatsUtil;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.letv.pp.func.CdeHelper;
import com.letv.pp.service.CdeService;
import com.lvideo.component.extraplayer.LVideoVideoViewBuilder;
import com.lvideo.component.extraplayer.utils.MyPlayerConstant;
import com.novaplayer.LetvMediaPlayerControl;

import java.util.ArrayList;
import java.util.Timer;

/**
 * 用于控制直播的controller
 *
 * @author zhangshuo
 */
public class PlayLiveController implements OnClickListener, OnPreparedListener,
        OnCompletionListener, OnErrorListener, OnBufferingUpdateListener, OnInfoListener,
        OnTouchListener {

    private final static String TAG = "PlayLiveController";

    private String mLiveLinkshellUrl = "";

    /**
     * 因为一个电视台的直播地址有多条，所以标示当前播放到了第几条数据.默认从头开始播放
     */
    private int mLivePosition = 0;

    private boolean mIsprepared = false;

    private boolean mIsReceiveError = false;

    /**
     * 是否是通过手势操作调节音量
     */
    private boolean mSystemHardKeyAdjustVolume = false;

    private PlayActivityLive mActivityLive;

    private PlayData mPlayData;

    private LVideoVideoViewBuilder mVideoViewBuilder;

    private TextView mTitleName;

    private TextView mNetRate;

    private TextView mPlayErrorView;

    private RelativeLayout mMediaControllerTop;

    private LinearLayout mPlayErrorLayout;

    private LinearLayout mLoadingLayout;

    /**
     * 播放器所处的位置
     */
    private RelativeLayout mVideoViewPosition;

    /**
     * 播放需要用到的View
     */
    private View mPlayerView;

    private LetvMediaPlayerControl mPlayContorl;

    private CDEManager mCDEManager;

    private CDEStatusReceiver mCdeStatusReiver;

    private android.content.DialogInterface.OnClickListener mDialogOnClickListener;

    private OnKeyListener mDialogOnKeyListener;

    private Window mWindow;

    protected PlayerTimer mPlayerTimer;

    private AudioManager mAudioManager;
    /**
     * 系统最大和最小音量
     */
    private final int VOLUME_UNINIT = -1;
    private final int VOLUME_MIN = 0;
    private static int VOLUME_MAX = 1500;
    /**
     * 是否静音
     */
    private boolean mIsSilent = false;

    public boolean isShow3GDialog = false;

    /**
     * 系统当前的声音值
     */
    private int mCurrentVolume = VOLUME_UNINIT;

    /**
     * 相关手势操作
     */
    protected LiveVieoPlayerGestureHandle mGestureHandle;

    private RelativeLayout mMediaController;

    protected AnimationDrawable loadingAnimationDrawable;

    /**
     * 大数据上报
     */
//    private BigDataPlayReporter bigDataPlayReporter;
    private String mLiveId;

    public PlayLiveController(PlayActivityLive mPlayLiveActivity) {
        mActivityLive = mPlayLiveActivity;
        mVideoViewBuilder = LVideoVideoViewBuilder.getInstants();
        initView();
        initData();
        initAudioVolume();
        setListener();
//        bigDataPlayReporter = new BigDataPlayReporter();
//        bigDataPlayReporter.setNt(BigDataUtils.getNetType(mActivityLive));
//        bigDataPlayReporter.setStreamType("flv_1000");
//        bigDataPlayReporter.setVlen();
//        bigDataPlayReporter.setPlayType(BigDataConstants.TY_TVLINE);
//        bigDataPlayReporter.setOwner(BigDataConstants.OWNER_IN); // 乐视源(包括直播)
    }

    private void initView() {
        // 选集面板这里面直播不需要
        mTitleName = (TextView) mActivityLive.findViewById(R.id.tv_video_title);
        mNetRate = (TextView) mActivityLive.findViewById(R.id.loading_net_rate);
        mMediaController =
                (RelativeLayout) mActivityLive.findViewById(R.id.mediacontroller_content);
        mPlayErrorView = (TextView) mActivityLive.findViewById(R.id.videoplayer_error_icon);
        mMediaControllerTop = (RelativeLayout) mActivityLive.findViewById(R.id.mediacontroller_top);
        mVideoViewPosition = (RelativeLayout) mActivityLive.findViewById(R.id.videoview_position);
        mLoadingLayout = (LinearLayout) mActivityLive.findViewById(R.id.layout_loading);
        mPlayErrorLayout = (LinearLayout) mActivityLive.findViewById(R.id.videoplayer_error_layout);

        if (mActivityLive.getmSysAPILevel() >= PlayerUtils.API_14) {
            // 设置虚拟键显示和隐藏的监听
            mWindow = mActivityLive.getmWindow();
        }
        if (null == mGestureHandle) {
            mGestureHandle =
                    new LiveVieoPlayerGestureHandle(mActivityLive, mMediaController, this, mHandler);
        }
        setControllerUIIdle();
    }

    private void setListener() {
        mMediaControllerTop.setOnTouchListener(this);
        mVideoViewPosition.setOnTouchListener(this);
        mPlayErrorView.setOnClickListener(this);
    }

    /**
     * 设置控制台面板为初始状态 zhangshuo 2015年2月4日 上午11:01:03
     */
    private void setControllerUIIdle() {
        showMediaControll(false);
        setPlayLoadingVisibile(true);
        setPlayErrorLayoutVisibile(false);
    }

    private void initData() {
        mCDEManager = CDEManager.getInstance(MoviesApplication.getInstance());
        mDialogOnClickListener = new ExitDialogOnClickListener();
        mDialogOnKeyListener = new ExitOnKeyListener();
        startPlayerTimer();
    }

    public void setmPlayData(PlayData playData) {
        this.mPlayData = playData;
        // TODO lid设置
//        mLiveId = mPlayData.getmLiveId();
        mLiveId = "-";
//        bigDataPlayReporter.setCid(mLiveId)
//                .setPid(mLiveId).setVid(mLiveId).setLid(mLiveId);
        if (null != mPlayData) {
            setTitleName(mPlayData.getmViewName());
            // 如果当前播放器准备成功，则开始播放直播数据
            if (prepareLivePlayer()) {
                // 初始化直播数据位置
                mLivePosition = 0;
                checkCDEStatus();
            }
        }
    }

    private boolean isStreamListEnd(ArrayList<String> streams) {
        boolean isEnd = false;
        try {
            if (mLivePosition >= 0 && mLivePosition < (streams.size() - 1)) {
                isEnd = false;
            } else {
                isEnd = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isEnd;
    }

    private void checkCDEStatus() {
        CdeHelper cdeHelper = mCDEManager.getmCdeHelper();
        LogUtils.e("wym", "!!!!!!!CDE服务是否成功启动!!!!!!!!!!!!" + cdeHelper.isReady());
        if (cdeHelper.isReady()) {
            playLiveSource();
        } else {
            mCdeStatusReiver = new CDEStatusReceiver();
            mActivityLive.registerReceiver(mCdeStatusReiver, new IntentFilter(
                    CdeService.ACTION_CDE_READY));
            mCDEManager.startCde();
        }
    }

    /**
     * 播放直播资源 zhangshuo 2015年2月4日 下午2:47:20
     */
    private void playLiveSource() {
        ArrayList<String> streams = mPlayData.getLiveStreams();
        if (null != streams && streams.size() > 0) {
            String liveOrgUrl = streams.get(mLivePosition);
            String result = getLiveUrl(liveOrgUrl);
            LogUtils.e("wym", "!!!!!!!!!当前播放的直播地址!!!!!!!" + result);
            setVideoPath(result);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Utils.PROGRESS_CHANGE:
                    showNetRate();
                    break;
                case Utils.DISSMISS_MEDIACONTROLLER:
                    dissMissMediaControll();
                    break;
                case Utils.VIDEO_DISMISS_GESTURE_POPUPWINDOW:
                    if (null != mGestureHandle) {
                        mGestureHandle.dismissGesturePopupWindow();
                    }
                    mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                            Utils.MEDIA_CONTROLLER_DISMISS_TIME);
                    break;
                default:
                    break;
            }
        }
    };

    private void setTitleName(String name) {
        if (null != mTitleName) {
            if (!TextUtils.isEmpty(name)) {
                mTitleName.setVisibility(View.VISIBLE);
                mTitleName.setText(name);
            } else {
                mTitleName.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 获取直播的播放地址
     *
     * @param orgLiveUrl
     * @return zhangshuo 2015年2月3日 下午3:46:21
     */
    private String getLiveUrl(String orgLiveUrl) {
//        LogUtils.e("wym", "live cde called and cur uuid " + bigDataPlayReporter.getUUID());
//        bigDataPlayReporter.genUUID(); // 在拿到cde调度地址时，构造当前播放器uuid
        LogUtils.e("wym", "!!!!!!!!!!!!!!!!!!!!!before addPlatCode orgLiveUrl is " + orgLiveUrl);
//        bigDataPlayReporter.setRef(orgLiveUrl);
//        bigDataPlayReporter.setPy(mPlayData.getmViewName(),
//                "live");
        if (!TextUtils.isEmpty(orgLiveUrl) && isLVideoStream(orgLiveUrl)) {
            StringBuffer sbff = new StringBuffer();
            sbff.append(orgLiveUrl);
            sbff.append("&platid=");
            sbff.append(PlayerUtils.PLATID);
            sbff.append("&splatid=");
            sbff.append(PlayerUtils.SPLATID);
//            sbff.append("&liveid=" + mLiveId);
//            sbff.append("&uuid=" + bigDataPlayReporter.getUUID());
            String liveUrL = sbff.toString();
            LogUtils.e("wym", "!!!!!!!!!!!!!!!!!!!!!after addPlatCode liveUrL is " + liveUrL);
            CdeHelper cdeHelper = mCDEManager.getmCdeHelper();
            mLiveLinkshellUrl = cdeHelper.getLinkshellUrl(liveUrL);
            return cdeHelper.getPlayUrl(mLiveLinkshellUrl);
        }
        return orgLiveUrl;
    }

    private boolean isLVideoStream(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        return url.contains("letv.com") || url.contains("letv.con")
                || url.contains("video123456.com");
    }

    private boolean prepareLivePlayer() {
        try {
            removeCurrPlayerView();
            // 直播数据默认采用m3u8播放器播放
            mPlayContorl = mVideoViewBuilder.build(mActivityLive, MyPlayerConstant.MOBILE_MY_M3U8);
            mPlayerView = mPlayContorl.getView();
            // 将播放器对象添加至容器中
            mVideoViewPosition.addView(mPlayerView);
            setPlayerListener();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 设置播放器的相关监听事件 zhangshuo 2015年2月3日 下午3:44:40
     */
    private void setPlayerListener() {
        mPlayContorl.setOnPreparedListener(this);
        mPlayContorl.setOnCompletionListener(this);
        mPlayContorl.setOnBufferingUpdateListener(this);
        mPlayContorl.setOnErrorListener(this);
        mPlayContorl.setOnInfoListener(this);
        mVideoViewPosition.setOnTouchListener(this);
    }


    private void setVideoPath(String playUrl) {
        mIsprepared = false;
        mActivityLive.isFromBackground = false;
        mIsReceiveError = false;
        LogUtils.e("wym", "!!!!!!!!mLivePosition!!!!!!!!!!!" + mLivePosition);
        if (!TextUtils.isEmpty(playUrl)) {
            mPlayContorl.setVideoPath(playUrl);
//            bigDataPlayReporter.setUrl(playUrl);
//            LogUtils.e("wym", "setVideoUri() called and cur uuid " + bigDataPlayReporter.getUUID());
//            bigDataPlayReporter.onPlayStart();
            // 播放时暂停下载
            PlayerUtils.sendPlayingBroadcast(mActivityLive);
        }
    }

    public void onResume() {
        // Toast.makeText(mActivityLive, "!!!!!onResume!!!!!!", Toast.LENGTH_LONG).show();
        LogUtils.e("wym", "!!!!onResume mActivityLive.isFromBackground!!!!"
                + mActivityLive.isFromBackground);
        if (mActivityLive.isFromBackground)
//            bigDataPlayReporter.onUuidChange(); // 从后台切回前台更新uuid
        // Toast.makeText(mActivityLive,
        // "!!!!!mActivityLive.isFromBackground!!!!!!"+mActivityLive.isFromBackground,
        // Toast.LENGTH_LONG).show();
        // 只有之前缓冲
        if (null != mActivityLive && !mIsReceiveError
                && (!isShow3GDialog || mActivityLive.isFromBackground)) {
            continePlayLvie();
        }
    }

    public void continePlayLvie() {
        isShow3GDialog = false;
        if (null == mPlayContorl) {
            prepareLivePlayer();
        }
        setControllerUIIdle();
        startPlayerTimer();
        checkCDEStatus();
    }

    public void onPause() {
        // Toast.makeText(mActivityLive, "!!!!!onPause!!!!!!", Toast.LENGTH_LONG).show();
        LogUtils.e("wym", "!!!!!!!!!onPause!!!!!!!!");
//        bigDataPlayReporter.setAc(BigDataConstants.PLAY_AC_BACKGROUND);
//        bigDataPlayReporter.onPlayProcess();
        // 目前mIsReceiveError为true 只有一种情况,即当所有地址均尝试过后.弹出错误提示框用户还没有点击重试时
        if (!mIsReceiveError) {
            playerExitCompletely();
        }
    }

    /**
     * 退出的Dialog监听
     *
     * @author zhangshuo
     */
    private class ExitDialogOnClickListener implements DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            exitForDialog();
        }
    }

    private class ExitOnKeyListener implements DialogInterface.OnKeyListener {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            LogUtils.e("wym", "!!!!ExitOnKeyListener!!!!!!!");
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                dialog.dismiss();
                exitForDialog();
            }
            return false;
        }
    }

    private void exitForDialog() {
        exitNormal();
        if (null != mActivityLive) {
            mActivityLive.finish();
        }
    }

    public void exitNormal() {
        mIsprepared = false;
        LogUtils.e("wym", "!!!!!!!exitNormal!!!!!!");
//        bigDataPlayReporter.onPlayEnd(); // 成功退出
        playerExitCompletely();
        removeCurrPlayerView();
    }

    private void removeCurrPlayerView() {
        // 根据当前的播放器类型创建播放器View
        if (null != mPlayerView) {
            mVideoViewPosition.removeView(mPlayerView);
        }
    }

    private class CDEStatusReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null == intent) {
                return;
            }

            if (CdeService.ACTION_CDE_READY.equals(intent.getAction())) {
                LogUtils.e("wym", "!!!!!!!!!!CDE成功启动!!!!!!!!!!!!!!!!!");
                unRegisterReceiver();
                playLiveSource();
            }
        }
    }

    public void unRegisterReceiver() {
        if (null != mActivityLive && null != mCdeStatusReiver) {
            mActivityLive.unregisterReceiver(mCdeStatusReiver);
            mCdeStatusReiver = null;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!mIsprepared) {
            return false;
        }
        switch (v.getId()) {
            case R.id.mediacontroller_top:
                return true;
            case R.id.videoview_position:
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    dynamicShowControll();
                }

                if (null != mGestureHandle) {
                    mGestureHandle.handleGestureSlide(event, mPlayContorl);
                }
                return true;
            default:
                break;
        }
        return false;
    }

    private void dynamicShowControll() {
        if (mMediaControllerTop.isShown()) {
            dissMissMediaControll();
        } else {
            showMediaControll(true);
        }
    }

    /**
     * 展现控制栏 zhangshuo 2014年5月4日 下午8:41:41
     */
    private void showMediaControll(boolean isDelayDismiss) {
        if (null != mActivityLive) {
            mActivityLive.statusBarShow(true);
//            mActivityLive.statusBarShow(false);
            if (mActivityLive.getmSysAPILevel() >= PlayerUtils.API_14) {
                PlayerUtils.showVirtualKey(mWindow);
            }
        }
        setMediaControllerTopVisibile(true);
        if (isDelayDismiss) {
            sendHideControMsg();
        }
    }


    /**
     * 隐藏控制栏 zhangshuo 2014年5月4日 下午8:42:00
     */
    private void dissMissMediaControll() {
        mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
        if (null != mActivityLive) {
            mActivityLive.statusBarShow(false);
            // 隐藏虚拟键操作
            if (mActivityLive.getmSysAPILevel() >= PlayerUtils.API_14) {
                PlayerUtils.hideVirtualKey(mWindow);
            }
        }
        setMediaControllerTopVisibile(false);
    }


    private void sendHideControMsg() {
        mHandler.removeMessages(Utils.DISSMISS_MEDIACONTROLLER);
        mHandler.sendEmptyMessageDelayed(Utils.DISSMISS_MEDIACONTROLLER,
                Utils.MEDIA_CONTROLLER_DISMISS_TIME);
    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        LogUtils.e("wym", "!!!!onInfo!!!!what!!" + what);
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                LogUtils.e("wym", "!!!!onInfo!!!!!!MEDIA_INFO_BUFFERING_START");
                bufferStart();
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                LogUtils.e("wym", "!!!!onInfo!!!!!!MEDIA_INFO_BUFFERING_END");
                bufferEnd();
            case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
                LogUtils.e("wym", "!!!!onInfo!!!!!!MEDIA_INFO_VIDEO_TRACK_LAGGING");
                break;
            case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                LogUtils.e("wym", "!!!!onInfo!!!!!!MEDIA_INFO_BAD_INTERLEAVING");
                break;
            case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
                LogUtils.e("wym", "!!!!onInfo!!!!!!MEDIA_INFO_NOT_SEEKABLE");
                break;
            default:
                break;
        }
        return false;
    }

    private void bufferStart() {
        setPlayLoadingVisibile(true);
    }

    private void bufferEnd() {
        setPlayLoadingVisibile(false);
        startPlayer();
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        LogUtils.e("wym", "!!!!!!mp!!!!" + mp + "!!!!!!what!!!!!" + what + "!!!!!extra!!!!!!" + extra);
        // 收到错误后立即切换下一条Url，如果所有的播放地址均已尝试过了则弹出错误提示框从头开始
        handleLiveError();
        return false;
    }

    private void handleLiveError() {
        if (!mIsReceiveError) {
            mIsReceiveError = true;
            // 播放器首先完全退出
            playerExitCompletely();
            if (null != mPlayData) {
                ArrayList<String> streams = mPlayData.getLiveStreams();
                if (!isStreamListEnd(streams)) {
                    ++mLivePosition;
//                    LogUtils.e("wym", "retry next url called and cur uuid " + bigDataPlayReporter.getUUID());
//                    bigDataPlayReporter.onPlayEnd();// 手动切换剧集上报end动作
//                    bigDataPlayReporter.resetUUID();
                    LogUtils.e("wym", "!!!!onError!!!mLivePosition!!!" + mLivePosition);
                    continePlayLvie();
                } else {
                    setPlayLoadingVisibile(false);
                    // 已经尝试过所有的播放地址了，弹出错误提示框提示用用户重试
                    setPlayErrorLayoutVisibile(true);
//                    bigDataPlayReporter.onPlayError(BigDataConstants.VIDEO_NOT_FOUND_ERR); //无法找到有效视频地址
//                    bigDataPlayReporter.onPlayEnd(); // 播放失败，end上报
                }
            }
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
//        bigDataPlayReporter.onPlayEnd();
        // 由于直播属于持续的节目，如果收到播放完成的回调则判断当前直播是否还在播放，如果正在播放则忽略，没有播放则按出错处理
        if (!isVideoPlaying()) {
            handleLiveError();
        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
//        LogUtils.e("wym", "onPrepared() init called and cur uuid " + bigDataPlayReporter.getUUID());
//        bigDataPlayReporter.genUUID();
//        bigDataPlayReporter.onPlayerInit(); // 播放器初始化上报
//        bigDataPlayReporter.onBufferEnd();
        mIsprepared = true;
        setPlayLoadingVisibile(false);
        sendHideControMsg();
        startPlayer();
    }

    public void startPlayer() {
        if (null != mPlayContorl) {
            mPlayContorl.start();
        }
    }

    public void pausePlayer() {
        LogUtils.e("wym", "!!!!!mPlayContorl.isPlaying()!!!!!!" + mPlayContorl.isPlaying());
        if (null != mPlayContorl && mPlayContorl.isPlaying() && mPlayContorl.canPause()) {
            mPlayContorl.pause();
        }
    }

    public void stopPlayer() {
        if (null != mPlayContorl) {
            mPlayContorl.stopPlayback();
        }
    }

    private void stopCdeSource() {
        if (!TextUtils.isEmpty(mLiveLinkshellUrl)) {
            CdeHelper cdeHelper = mCDEManager.getmCdeHelper();
            cdeHelper.stopPlay(mLiveLinkshellUrl);
        }
    }

    /**
     * 播放器完全退出 zhangshuo 2015年2月3日 下午5:33:35
     */
    public void playerExitCompletely() {
        // 停止计时
        stopPlayerTimer();
        pausePlayer();
        stopPlayer();
        stopCdeSource();
    }

    public boolean isVideoPlaying() {
        if (null != mPlayContorl) {
            return mPlayContorl.isPlaying();
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 用户点击了出错重试按钮
            case R.id.videoplayer_error_icon:
                // 首先重置当前的播放位置
                mLivePosition = 0;
                // 然后选取当前位置的播放地址开始播放
                continePlayLvie();
                break;
            default:
                break;
        }
    }

    private void setMediaControllerTopVisibile(boolean flag) {
        if (null != mMediaControllerTop) {
            if (flag) {
                mMediaControllerTop.setVisibility(View.VISIBLE);
            } else {
                mMediaControllerTop.setVisibility(View.GONE);
            }
        }
    }

    private void setPlayLoadingVisibile(boolean flag) {
        if (null != mLoadingLayout) {
            if (flag) {
                if (!mLoadingLayout.isShown()) {
                    // 显示
                    mLoadingLayout.setVisibility(View.VISIBLE);
                    LogUtils.e("wym", "!!!!!!!!!!!!!!block!!!!!!!!!!!!!!");
//                    if (bigDataPlayReporter != null) {
//                        bigDataPlayReporter.setAc(BigDataConstants.PLAY_AC_BLOCK);
//                        bigDataPlayReporter.onPlayProcess();
//                    }
                }
            } else {
                if (mLoadingLayout.isShown()) {
                    // 不显示
                    mLoadingLayout.setVisibility(View.GONE);
                    LogUtils.e("wym", "!!!!!!!!!!!!!!eblock!!!!!!!!!!!!!!");
//                    if (bigDataPlayReporter != null) {
//                        bigDataPlayReporter.setAc(BigDataConstants.PLAY_AC_EBLOCK);
//                        bigDataPlayReporter.onPlayProcess();
//                    }
                }
            }
        }
    }

    /**
     * 显示当前网速 zhangshuo 2014年8月19日 下午2:12:27
     */
    private void showNetRate() {
        // 如果当前API level > 2.2则显示当前网速
        if (mActivityLive.getmSysAPILevel() >= PlayerUtils.API_8) {
            if (mLoadingLayout.isShown()) {
                String currentRate = TrafficStatsUtil.countCurRate();
                mNetRate.setVisibility(View.VISIBLE);
                mNetRate.setText(currentRate);
            }
        } else {
            mNetRate.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 开启计时器，秒刷新界面
     */
    protected void startPlayerTimer() {
        // 当前不是暂停状态并且播放器已经准备好了才开始刷新页面
        stopPlayerTimer();
        if (mPlayerTimer == null) {
            mPlayerTimer = new PlayerTimer(mHandler, Utils.PROGRESS_CHANGE);
            Timer m_musictask = new Timer();
            m_musictask.schedule(mPlayerTimer, 0, 1000);
        }
    }

    /**
     * 停止播放器计时
     */
    protected void stopPlayerTimer() {
        try {
            if (mPlayerTimer != null) {
                mPlayerTimer.cancel();
                mPlayerTimer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public PlayActivityLive getmActivityLive() {
        return mActivityLive;
    }

    public void setPlayErrorLayoutVisibile(boolean flag) {
        if (null != mPlayErrorLayout) {
            if (flag) {
                mPlayErrorLayout.setVisibility(View.VISIBLE);
            } else {
                mPlayErrorLayout.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        // TODO Auto-generated method stub

    }

    private void initAudioVolume() {
        mAudioManager = (AudioManager) mActivityLive.getSystemService(Context.AUDIO_SERVICE);
        VOLUME_MAX = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) * 100;
        int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 100;
        mIsSilent = (streamVolume == VOLUME_MIN);
        if (!mIsSilent || mCurrentVolume == VOLUME_UNINIT) {
            mCurrentVolume = streamVolume;
        }
    }

    /**
     * 设置当前的音量
     */
    public void setCurrentVolume(int volume) {
        if (volume > VOLUME_MAX) {
            volume = VOLUME_MAX;
        } else if (volume < VOLUME_MIN) {
            volume = VOLUME_MIN;
        }
        mCurrentVolume = volume;
        mIsSilent = (mCurrentVolume == VOLUME_MIN);

        updateCurrentVolumeDisplay();
    }

    /**
     * 更新系统音量以及音量进度条
     */
    private void updateCurrentVolumeDisplay() {
        if (mAudioManager == null) {
            return;
        }
        int targetVolume = mIsSilent ? 0 : mCurrentVolume;

        // mFullScreenVolumSeekBar.setProgress(targetVolume);
        if (mSystemHardKeyAdjustVolume) {
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (targetVolume / 100),
                    AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
            mSystemHardKeyAdjustVolume = false;
        } else {
            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (targetVolume / 100), 0);
        }
    }
}
